<?php
namespace Home\Controller;
use Think\Controller;
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';

//设置token 与微信平台的要一致
define("TOKEN", "amall"); 

$Wechat = A('Wechat');
if (isset($_GET['echostr'])) {
    $Wechat->valid();
}else{
    $Wechat->responseMsg();
}

class WechatController extends Controller {
	public function __construct()
    {
    	parent::__construct();
    }

    public function valid()  
	{
		$echoStr = I('get.echostr');  // //$_GET["echostr"]
		//valid signature , option   
		if($this->checkSignature())
		{
		    header('content-type:text');    
		    ob_clean();
		    echo $echoStr;
		    exit;   
		}  
	}

	//接收事件订阅与回复响应消息
	public function responseMsg()  
	{
	    //当用户关注我们公众账号的时候，微信公众平台会向我们推送一个PSET请求,而且是通过xml格式
	    //1.获取到微信推送过来的post数据(xml格式)  
		$postArr  = $GLOBALS['HTTP_RAW_POST_DATA'];
		//比如用户关注我们公众账号后，我们会发给用户如：欢迎光临，XXX关注我们的公众账号
		//2.处理消息类型，并设置回复类型和内容
		$postObj = simplexml_load_string($postArr);
		//判断该数据包是否是订阅的事件推送
		if(strtolower($postObj -> MsgType) == 'event')
		{
			//如果是关注 subscribe 事件
			if(strtolower($postObj -> Event == 'subscribe'))
			{
				//回复用户消息
				$toUser     = $postObj -> FromUserName;//发给该用户
				$fromUser   = $postObj -> ToUserName;//我们是开发者 发送给用户
				$time       = time();
				$msgtype    = 'text';
				$eventkey   = substr($postObj -> EventKey,8);//获取的到值如qrscene_25，我只要25这个user_id
				$content    = "欢迎关注amall微信公众号!";

				//成功获取到了$eventkey 就是分享二维码的用户user_id，给他送积分
				if($eventkey)
				{
					//判断是否有user_id
					$users = D('Users');
					$user_id = $users->where('user_id='.$eventkey)->getField('user_id');
					if($user_id)
					{
						$t_id = 2;
				        //添加积分
				        $pointmodel = D('PointsLog');
				        $type = 1;
				        $log_text = '分享二维码';
				        //改变积分
				        $log_id = $pointmodel->change_points($t_id,$user_id, $type, $log_text);
					}
					
				}

				
				$template = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[%s]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				</xml>";
				
				$info = sprintf($template,$toUser,$fromUser,$time,$msgtype,$content);
				echo $info;	
			}
		} 
	}

	private function checkSignature()  
	{   
		// you must define TOKEN by yourself   
		if (!defined("TOKEN")) 
		{    
			throw new Exception('TOKEN is not defined!');   
		}  
		$signature =  I('get.signature');//$_GET["signature"];
		$timestamp = I('get.timestamp');  //$_GET["timestamp"]
		$nonce     = I('get.nonce');   //$_GET["nonce"]
		$token     = TOKEN; 
		$tmpArr    = array($token, $timestamp, $nonce);  
		// use SORT_STRING rule   
		sort($tmpArr, SORT_STRING);  
		$tmpStr = implode( $tmpArr );   
		$tmpStr = sha1( $tmpStr );   
		if( $tmpStr == $signature )
		{
			return true; 
		}
		else
		{
			return false;   
		} 
   }

	//记录微信服务器传过来的参数
   function traceHttp()
   {
	   //$this->logger("REMOTE_ADDR: ". $_SERVER["REMOTE_ADDR"].(strpos($_SERVER["REMOTE_ADDR"],"101.226"))?"From WeiXin":"UNKnow IP");
	   $this->logger("REMOTE_ADDR: ". $_SERVER["REMOTE_ADDR"] . ((strpos($_SERVER["REMOTE_ADDR"],"101.226")) ? " From WeiXin " :  " UNKnow IP "));
	   $this->logger("QUERY_STRING: " . $_SERVER["QUERY_STRING"]);

	   //file_put_contents('weixin_log.txt', '$_GET[echostr])='.htmlspecialchars($_GET['echostr']).PHP_EOL,FILE_APPEND); //记录是否获取到echostr参数
       $this->logger("echostr: ".htmlspecialchars($_GET['echostr']));
       //exit(htmlspecialchars($_GET['echostr']));      //把echostr参数返回给微信开发者后台

   }
   //生成页面 方便查看
   function logger($content)
   {
	   file_put_contents("logg.html",date('Y-m-d H:i:s').$content."<br>",FILE_APPEND);
   }

   //获取access_token
   function get_accessToken()
   {
	   $appid     = "wx8173355ad26e6963";
	   $appsecret = "117db0cb85fba38b1e0f5b37a4062bdb";
	   $url       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;

	   $ch = curl_init();
	   curl_setopt($ch, CURLOPT_URL, $url);
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   curl_setopt($ch, CURLOPT_HEADER, 0);  
		
	   curl_setopt($ch, CURL_SSLVERSION_SSL, 2);  
	   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
	   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
	  
	   $data = curl_exec($ch);
		
	   $arr = json_decode($data, true);
	   //var_dump($arr);
		
	   curl_close($ch);
	   return $arr;
   }

   //返回access_token 保存的方法
   function getWx_access_token()
   {
        $res = file_get_contents('access_token.json');
        $result = json_decode($res, true);
        $this->expires_time = $result["expires_time"];
        $this->access_token = $result["access_token"];


        if (time() > ($this->expires_time + 3600)){
			$res = $this->get_accessToken();
            $this->access_token = $res["access_token"];
            $this->expires_time = time();
            file_put_contents('access_token.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->expires_time.'}');
        }
		return $this->access_token;
   }



   //创建微信自定义菜单
   public function definedItem()
   {
	   header('content-type:text/html;charset-=utf-8');
	   // https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
	   $access_token = $this->getWx_access_token();
	   //echo "the token is: ".$access_token."<br>";
	   //exit;
	   $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
	   //echo "the url is:".$url;
	   $jsonmenu = '{
					"button":
					[
					  {
						   "name":"会员管家",
						   "sub_button":[
							{
							   "type":"view",
							   "name":"会员注册",
							   "url":"http://amall.7woods.net/Home/UserCenter/register"
							},
							{
							   "type":"view",
							   "name":"会员中心",
							   "url":"http://amall.7woods.net/Home/UserCenter/member"
							},
							{
							   "type":"view",
							   "name":"会员礼遇",
							   "url":"http://amall.7woods.net/Home/Courtesy/card_list"
							},
							{
								"type":"view",
								"name":"联系我们",
								"url":"http://amall.7woods.net/Home/UserCenter/link_us"
							}]
					  
				
					   },
					   {
						   "name":"amall生活",
						   "sub_button":[
							{
							   "type":"view",
							   "name":"楼层导览",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"amall优惠",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"最新活动",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"飞扬影院",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"联系我们",
							   "url":"http://amall.7woods.net/Home/Index/index"
							}]
					   },
					   {
						   "name":"amall停车",
						   "sub_button":[
							{
							   "type":"view",
							   "name":"停车优惠",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"停车缴费",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"车位寻车",
							   "url":"http://amall.7woods.net/Home/Index/index"
							},
							{
							   "type":"view",
							   "name":"车位查询",
							   "url":"http://amall.7woods.net/Home/Index/index"
							}]
					   }
					 ]
			   }';
	   //print_r(urldecode(json_encode($postArr)));
	   //exit;
	   //$postJson = json_encode($postArr);
	   //$res =$this->http_curl($url,'post','json',$postJson);
	   $res = $this->request_post($url,$jsonmenu);
	   //var_dump($res);
   }

   function request_post($url = '', $param = '')
	{
		
		$ch = curl_init(); //初始化curl
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //跳过SSL证书检查。 
		curl_setopt($ch, CURLOPT_URL, $url); //抓取指定网页
		curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		$data = curl_exec($ch); //运行curl
		
		//echo "have a bug:".curl_error($ch);
		//var_dump(curl_error($data));
		
		curl_close($ch);
		
		
		return $data;
	}

	//微信授权登录 获取用户详细信息
	function getWc_user()
	{
		//1、获取code
		$appid     = "wx8173355ad26e6963";
		$redirect_uri = urlencode("http://amall.7woods.net/Home/Wechat/getUserinfo");
	    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect 
	    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	    header('location:'.$url);

	}

	function getUserinfo()
	{
		//2、通过code换取网页授权access_token
		$appid     = "wx8173355ad26e6963";
	    $appsecret = "117db0cb85fba38b1e0f5b37a4062bdb";
	    $code = $_GET['code'];
		// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
		$res = $this->http_getCurl($url);
		//var_dump($res);
		//exit;
		$access_token = $res['access_token'];
		$openid = $res['openid'];
		//3、拉取用户的详细信息
		//http：GET（请使用https协议） https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN ";
		$res = $this->http_getCurl($url);
		//var_dump($res);
		//把获取到是数据传给login
		$user = A('UserCenter');
		$user->login($res);

	}
	function http_getCurl($url)
    {
	   $ch = curl_init();
	   curl_setopt($ch, CURLOPT_URL, $url);
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   curl_setopt($ch, CURLOPT_HEADER, 0);  
		
	   curl_setopt($ch, CURL_SSLVERSION_SSL, 2);  
	   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
	   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
	  
	   $data = curl_exec($ch);
		
	   $arr = json_decode($data, true);
	   //var_dump($arr);
		
	   curl_close($ch);
	   return $arr;
    }

    //获取jsapi_ticket
    function getTicket()
    {
    	if($_SESSION['jsapi_ticket_expire_time'] > time() && $_SESSION['jsapi_ticket'])
    	{
    		$jsapi_ticket = $_SESSION['jsapi_ticket'];
    	}
    	else
    	{
    		$access_token = $this->getWx_access_token();
	    	$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
	    	$res = $this->http_getCurl($url);
	    	$jsapi_ticket = $res['ticket'];
	    	$_SESSION['jsapi_ticket'] = $jsapi_ticket;
	    	$_SESSION['jsapi_ticket_expire_time'] = time()+7000;
    	}
    	return $jsapi_ticket;
    }
    //获取随机码
    function getrank($num = 16)
    {
    	$array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    		           'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    		           '0','1','2','3','4','5','6','7','8','9'
    		);
    	$tmpstr = '';
    	$max = count($array);
    	for($i=1;$i<=$num;$i++)
    	{
    		$key = rand(0,$max-1);//'A' -> $array[0]
    		$tmpstr .= $array[$key];
    	}
    	return $tmpstr;
    }

    //分享amall优惠活动
    function sharewx()
    {
    	//1、获取jsapi_ticket票据
    	$jsapi_ticket = $this->getTicket();
    	$timestamp = time();
    	$nonceStr  = $this->getrank();

    	//$url = "http://amall.7woods.net/Home/Index/index";
    	//$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
    	$protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
    	//2.获取signature
    	$signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;

    	$signature = sha1($signature);

    	$shdat['jsapi_ticket'] = $jsapi_ticket;
    	$shdat['timestamp']    = $timestamp;
    	$shdat['nonceStr']     = $nonceStr;
    	$shdat['signature']    = $signature;

    	return $shdat;
    }

    //分享二维码 临时二维码 参考接口https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
    function shareqr()
    {
    	//1.获取ticket票据，跟上面的获取jsapi_ticket是两码事
    	$access_token = $this->getWx_access_token();
    	$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
    	//POST数据例子：{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
    	$arr = array(
    		'expire_seconds' => 604800,//24*60-60*7
    		'action_name'    => "QR_SCENE",
    		'action_info'    => array('scene' => array('scene_id'  => session('user_id')))//把用户id传过去
    	);
    	$arr = json_encode($arr);
    	$res = $this->request_post($url,$arr);
    	//var_dump($res);
    	$data = json_decode($res, true);//要转成json获取
    	//通过ticket获取二维码图片
    	$ticket = $data['ticket'];
    	//HTTP GET请求（请使用https协议）https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET提醒：TICKET记得进行UrlEncode
    	$img = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
    	//echo $img;
    	//$qrimg = $this->http_getCurl($url);
    	//ticket正确情况下，http 返回码是200，是一张图片，可以直接展示或者下载
    	//echo "<img src='".$img."'/>";
    	return $img;
    }

}